package com.simplegui.examples.ricerocks;

import static com.simplegui.examples.ricerocks.RiceRocksConfigurations.*;

import java.awt.Point;

import com.simplegui.api.Canvas;
import com.simplegui.api.GameComponent;
import com.simplegui.api.ImageFile;
import com.simplegui.api.ImageInfo;
import com.simplegui.api.Sound;
import com.simplegui.api.util.MathUtils;

public class Sprite implements GameComponent{
	
	private Double[] pos;
	private Double[] vel;
	private double angle;
	private double angle_vel;
	private ImageInfo imageInfo;
	private ImageFile imageFile;
	private int age;
	
	public Sprite(Double[] pos, Double[] vel, double angle, double angle_vel, ImageInfo imageInfo, ImageFile imageFile, Sound sound) {
		super();
		this.pos = pos;
		this.vel = vel;
		this.angle = angle;
		this.angle_vel = angle_vel;
		this.imageInfo = imageInfo;
		this.imageFile = imageFile;
		this.age = 0;
		if (sound != null){
			sound.rewind();
			sound.play();
		}
	}


	@Override
	public void executeLogic() {
      // update angle
      angle += angle_vel;
      
      // update position
      pos[0] = (pos[0] + vel[0]) % WIDTH;
      pos[1] = (pos[1] + vel[1]) % HEIGHT;
      
      age += 1;
      
	}


	@Override
	public void draw(Canvas canvas) {
      if (imageInfo.isAnimated()){
    	  int[] image_index = {age % imageInfo.getSize().width, (age / imageInfo.getSize().width) % imageInfo.getSize().height};
    			  canvas.drawImage(imageFile, 
    					  new Point((int)(imageInfo.getCenter().x + image_index[0] * imageInfo.getSize().getWidth())
    							   ,(int)(imageInfo.getCenter().y + image_index[1] * imageInfo.getSize().getHeight()))
    			  		 ,imageInfo.getSize(), getPosition(), imageInfo.getSize());
      }else{
    	  canvas.drawImage(imageFile, imageInfo.getCenter(), imageInfo.getSize(), getPosition(), imageInfo.getSize(), angle);

      }
		
	}
	
	public ImageInfo getImageInfo() {
		return imageInfo;
	}
	
	public boolean collide(GameComponent other){
		double distance = MathUtils.dist(getPosition(), getPosition());
		boolean result = distance < getRadius() + other.getRadius();
		if (result){
			explosion_sound.rewind();
			explosion_sound.play();
		}
		return result;
	}
	
	public boolean isAlive(){
		return imageInfo.getLifespan() > age;
	}


	@Override
	public Point getPosition() {
		return new Point(pos[0].intValue(), pos[1].intValue());
	}


	@Override
	public double getRadius() {
		return imageInfo.getRadius();
	}
}
